package back.Java代理.动态代理.jdk动态代理.案例2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;

public class TestDynamicProxy {
    public static void main(String[] args) {
        // 将生成的代理类文件保存在当前工作目录
        // System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        byte[] proxyClassByte = ProxyGenerator.generateProxyClass(
                "$Proxy0",
                new Class<?>[] { Subject.class });
        // 保存字节码到文件
        try (FileOutputStream fos = new FileOutputStream("$Proxy0.class")) {
            fos.write(proxyClassByte);
            System.out.println("代理类已保存为 $Proxy0.class");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建目标对象
        Subject realSubject = new RealSubject();
        Subject proxy = (Subject) Proxy.newProxyInstance(
                Subject.class.getClassLoader(),
                new Class<?>[] { Subject.class },
                new DynamicProxyHandler(realSubject));
        proxy.request();
    }
}
